<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class CrontabController extends Controller
{
    /**
     * 爬取东方财富直播100条数据
     */
    public function eastMoney()
    {
        $html = file_get_contents(
            "http://newsapi.eastmoney.com/kuaixun/v1/getlist_zhiboall_ajaxResult_100_1_.html");
        if (strpos((string)$html, "ajaxResult")) {
            list($foo, $json) = explode("ajaxResult=", $html);
            $data = json_decode($json, true);
            $dataName = INDEX_INFORMATION_STORAGE_NAME;
            if ($data) {
                echo "<pre>";
                $list = $data["LivesList"] ?? [];
                Redis::ltrim($dataName, 1, 0);
                foreach ($list as $v) {
                    Redis::rpush($dataName, serialize(["title" => $v["digest"] ? $v["digest"] : $v["title"],
                        "time" => date("Y-m-d H:i", strtotime($v["showtime"]))]));
                }
            }
        }
    }

    /**
     * 爬取新浪股市及时雨100条数据
     */
    public function sina()
    {
        $newData = [];
        for ($i = 1; $i <= 3; $i++) {
            $html = file_get_contents(
                "http://roll.finance.sina.com.cn/finance/zq1/gsjsy/index_{$i}.shtml");
            $html = iconv("gbk", "utf8", (string)$html);
            preg_match_all("/<a.*?>(.*?)<\/a><span>\((.*?)\)<\/span><\/li>/", $html, $match);

            foreach ($match[1] ?? [] as $k => $v) {
                if (count($newData) > 99) break;
                $time = date("Y") . "-" . str_replace("月", "-",
                        str_replace("日", "", $match[2][$k]));
                $newData[] = ["title" => $v, "time" => $time];
            }
        }

        if ($newData) {
            $dataName = INDEX_COMMENTS_STORAGE_NAME;
            Redis::ltrim($dataName, 1, 0);
            foreach ($newData as $v) {
                Redis::rpush($dataName, serialize($v));
            }
        }
    }
}